/**
 * 
 */
package com.hanhai.zrb.api.facade.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hanhai.zrb.api.biz.service.CommonCounterService;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.api.biz.util.DateUtil;
import com.hanhai.zrb.api.client.facade.FundFacade;
import com.hanhai.zrb.model.common.CommonCounterKey;
import com.hanhai.zrb.model.common.SysDictionary;
import com.hanhai.zrb.model.common.enums.ProvinceEnum;
import com.hanhai.zrb.model.common.enums.StatusEnums;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.fund.dto.FundDto;
import com.hanhai.zrb.model.fund.vo.AppFundDetailVo;
import com.hanhai.zrb.model.fund.vo.AppFundVo;
import com.hanhai.zrb.model.project.Industry;
import com.hanhai.zrb.model.user.UserStatisticDetail;


@WebService(endpointInterface = "com.hanhai.zrb.api.client.facade.FundFacade", serviceName = "FundFacade")
@Service("fundFacade")
public class FundFacadeImpl implements FundFacade {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private FundService fundService;
	
	@Resource
	private SysDictionaryService sysDictionaryService;
	
	@Resource
	private IndustryService industryService;
	
	@Resource
	private CommonCounterService commonCounterService;

	@Override
	public List<AppFundVo> listAppFunds(Date pushTime,Integer limit,Boolean forward) {
		FundDto dto = new FundDto();
		dto.setState(StatusEnums.RELEASE.getCode());
		if(forward){
			dto.setStartTime(pushTime);
		}else{
			dto.setEndTime(pushTime);
		}
		dto.setPageNum(1);
		dto.setPageSize(limit);
		List<Fund> fundList = fundService.queryByCondition(dto);
		return buildAppFundVo(fundList);
	}
	
	@Override
	public List<AppFundVo> listAppFunds(Long userId, Date pushTime,
			Integer limit, Boolean forward) {
		FundDto dto = new FundDto();
		dto.setState(StatusEnums.RELEASE.getCode());
		if(forward){
			dto.setStartTime(pushTime);
		}else{
			dto.setEndTime(pushTime);
		}
		dto.setUserId(userId);
		dto.setPageNum(1);
		dto.setPageSize(limit);
		List<Fund> fundList = fundService.queryByCondition(dto);
		return buildAppFundVo(fundList);	}
	
	
	@Override
	public AppFundDetailVo getAppFundDetail(Long id) {
		AppFundDetailVo vo = null;
		Fund fund = fundService.findById(id);
		if(null!=fund){
			vo = new AppFundDetailVo();
			vo.setPic(fund.getPic());
			vo.setId(fund.getId());
			vo.setDesc(fund.getDescrition());
			vo.setFundNo(fund.getFundNo());
			vo.setRequirement(fund.getRequirement());
			vo.setTitle(fund.getTitlesVal());
			if(null!=fund.getPushTime()){
				vo.setPushDate(DateUtil.dateToString(fund.getPushTime()));
				vo.setWeekDay(DateUtil.getWeekOfDate(fund.getPushTime()));
			}
			if(null!=fund.getTotal()){
				vo.setTotal(new BigDecimal(fund.getTotal()).setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			if(null!=fund.getAuth()){
				vo.setAuthName(sysDictionaryService.getByCodeFromLocalCache(fund.getAuth().toString()).getItemName());
			}
			if(null!=fund.getInvestMode()){
				vo.setModeName(sysDictionaryService.getByCodeFromLocalCache(fund.getInvestMode().toString()).getItemName());
			}
			
			CommonCounterKey commonCounterKey = new CommonCounterKey();
			commonCounterKey.setMainKey(UserStatisticDetail.Type.fund_col.getCountKey());
			commonCounterKey.setSecondaryKey(String.valueOf(id));
			vo.setCollectNum(commonCounterService.getCurrentCountByKey(commonCounterKey));
			
			commonCounterKey.setMainKey(UserStatisticDetail.Type.fund_advisory.getCountKey());
			vo.setQueryNum(commonCounterService.getCurrentCountByKey(commonCounterKey));
			
			commonCounterKey.setMainKey(UserStatisticDetail.Type.fund_share.getCountKey());
			vo.setShareNum(commonCounterService.getCurrentCountByKey(commonCounterKey));
			
			if(StringUtils.isNoneBlank(fund.getDestination())){
				if(fund.getDestination().equals("0")){
					vo.setAreas("全国");
				}else{
					String[] destIds = fund.getDestination().split("#");
					String areas = "";
					for(String destId:destIds){
						if(!"".equals(areas)){
							areas=areas+"/"+ProvinceEnum.getProvinceName(Integer.valueOf(destId));
						}else{
							areas=ProvinceEnum.getProvinceName(Integer.valueOf(destId));
						}
					}
					vo.setAreas(areas);
				}
				
			}
			
			if(StringUtils.isNoneBlank(fund.getIndustryId())){
				String[] ids = fund.getIndustryId().split("#");
				Map<Integer,Industry> map = industryService.selectAllMap();
				String industryName ="";
				for(String industryId:ids){
					if(!"".equals(industryName)){
						industryName=industryName+"/"+map.get(Integer.valueOf(industryId)).getIndustryName();
					}else{
						industryName=map.get(Integer.valueOf(industryId)).getIndustryName();
					}
				}
				vo.setIndustryName(industryName);
			}
		}
		
		return vo;
	}
	
	
	private List<AppFundVo> buildAppFundVo(List<Fund> fundList){
		List<AppFundVo> voList = new ArrayList<AppFundVo>();
		try {
		if(CollectionUtils.isNotEmpty(fundList)){
			SysDictionary sys = new SysDictionary();
			Map<String,SysDictionary> map = sysDictionaryService.getItemsMap(sys);
			Map<Integer,Industry> industryMap = industryService.selectAllMap();
			
			List<String> idList = new ArrayList<String>();
			for (int i = 0; i < fundList.size(); i++) {
				if(null!=fundList.get(i).getId()){
					idList.add(String.valueOf(fundList.get(i).getId()));
				}
				
			}
			
			Map<String,Long> countMap = commonCounterService.listCountMapBySecondaryKeyList(UserStatisticDetail.Type.fund_col.getCountKey(), idList);
			
			
			for(Fund fund:fundList){
				AppFundVo vo = new AppFundVo();
				vo.setPic(fund.getPic());
				vo.setId(fund.getId());
				vo.setTitle(fund.getTitlesVal());				
				vo.setTotal(fund.getTotal());
				vo.setPushTime(fund.getPushTime());
				if(StringUtils.isNoneBlank(fund.getDestination())){
					String[] destIds = fund.getDestination().split("#");
					String areas = "";
					for(String id:destIds){
						if(!"".equals(areas)){
							areas=areas+"/"+ProvinceEnum.getProvinceName(Integer.valueOf(id));
						}else{
							areas=ProvinceEnum.getProvinceName(Integer.valueOf(id));
						}
					}
					vo.setAreas(areas);
				}
				
				if(null!=fund.getPushTime()){
					vo.setPeriod(DateUtil.getExactQuot(DateUtil.dateToStringFullFormat(new Date()), DateUtil.dateToStringFullFormat(fund.getPushTime())));
				}
				
				if(null!=fund.getAuth()&&null!=map.get(fund.getAuth().toString())){
					vo.setAuth(fund.getAuth());
					vo.setAuthName(map.get(fund.getAuth().toString().trim()).getItemName());
				}
				
				if(StringUtils.isNoneBlank(fund.getIndustryId())){
					String[] ids = fund.getIndustryId().split("#");
					String industryName ="";
					for(String industryId:ids){
						if(!"".equals(industryName)){
							industryName=industryName+"/"+industryMap.get(Integer.valueOf(industryId)).getIndustryName();
						}else{
							industryName=industryMap.get(Integer.valueOf(industryId)).getIndustryName();
						}
					}
					vo.setIndustryName(industryName);
				}
				if(null!=fund.getInvestMode() && null!=map.get(fund.getInvestMode().toString())){
					vo.setInvestMode(map.get(fund.getInvestMode().toString()).getItemName());
				}
				
				Long tempCount = countMap.get(String.valueOf(fund.getId()));
				if(tempCount == null){
					tempCount = 0L;
				}
				vo.setCollectNum(tempCount);
				voList.add(vo);
			}
		}
		} catch (ParseException e) {
			logger.error("get fund list from app failed because parse error");
		}
		return voList;
	}

	@Override
	public List<AppFundVo> searchAppFunds(Date pushTime, List<String> destinationList,
			List<String> industrysList,String mode, Integer limit, Boolean forward) {
		FundDto dto = new FundDto();
		
		dto.setState(StatusEnums.RELEASE.getCode());
		if(forward){
			dto.setStartTime(pushTime);
		}else{
			dto.setEndTime(pushTime);
		}
		if(CollectionUtils.isNotEmpty(industrysList)){
			dto.setIndustrysList(industrysList);
		}
		if(CollectionUtils.isNotEmpty(destinationList)){
			dto.setDestinationList(destinationList);
		}
		dto.setPageNum(1);
		if( null == limit){
			limit = 20;
		}
		if(StringUtils.isNumeric(mode)){
			dto.setInvestMode(Integer.valueOf(mode));
		}
		
		dto.setPageSize(limit);
		List<Fund> fundList = fundService.queryByCondition(dto);
		return buildAppFundVo(fundList);
	}

	
	
	
	
}
